﻿using Engine;
using Game;
using Game.NetWork;
using Game.NetWork.Packages;
using Game.Server;
using Game.Server.Event;
using Game.Server.PlayerEvent;
using GameEntitySystem;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace Game.Server.Plugins
{
    public class qy : ServerPlugin, ICreatureSpawnEventHandle, IPlayerEnterGameEventHandle, ICreatureHealthEventHandle
    {
        public override int Version => 10;

        static public string path { private set; get; } = "AreaName.json";

        public static SubsystemPlayers SubsystemPlayers;

        public static Dictionary<string, List<AreaInfo>> 配置字典 = new Dictionary<string, List<AreaInfo>>();

        public static Dictionary<string, List<AreaInfo2>> 内存字典 = new Dictionary<string, List<AreaInfo2>>();

        private static Dictionary<ComponentPlayer, string> 玩家当前区域 = new Dictionary<ComponentPlayer, string>();

        public class AreaInfo
        {
            public Dictionary<string, string> 区域一 = new Dictionary<string, string>();
            public Dictionary<string, string> 区域二 = new Dictionary<string, string>();
            public string 进入区域消息 = "";
            public string 离开区域消息 = "";
            public bool 是否无敌 { get; set; } = false;
        }

        public class AreaInfo2
        {
            public Dictionary<string, Vector3> 区域一 = new Dictionary<string, Vector3>();
            public Dictionary<string, Vector3> 区域二 = new Dictionary<string, Vector3>();
            public string 进入区域消息 = "";
            public string 离开区域消息 = "";
            public bool 是否无敌 { get; set; } = false;
        }

        public static void 初始化()
        {
            if (File.Exists(path))
            {
                Log.Information("AreaName已创建");
            }
            else
            {
                Log.Information("AreaName未创建");
                //创建AreaName.json文件
                var areaName = new Dictionary<string, List<AreaInfo>>()
                {
                    {"Area1",new List<AreaInfo>{{new AreaInfo {
                        区域一 = new Dictionary<string, string>() { { "最低点", "1,7,4" } },
                        区域二 = new Dictionary<string, string> { {"最高点","1,7,8" } },
                        进入区域消息 = "欢迎来到区域1" ,
                        离开区域消息 = "您已离开区域1",
                        是否无敌 = true
                    } } } },
                    {"Area2",new List<AreaInfo>{{new AreaInfo {
                        区域一 = new Dictionary<string, string>() { { "最低点", "10,7,10" } },
                        区域二 = new Dictionary<string, string> { {"最高点","15,10,15" } },
                        进入区域消息 = "欢迎来到区域2" ,
                        离开区域消息 = "您已离开区域2",
                        是否无敌 = false
                    } } } }
                };

                JsonConvert.SerializeObject(areaName, Formatting.Indented);
                File.WriteAllText(path, JsonConvert.SerializeObject(areaName, Formatting.Indented));
                Log.Information("AreaName已创建");
            }
        }

        public static void 加载配置()
        {
            try
            {
                string json = File.ReadAllText(path);
                配置字典 = JsonConvert.DeserializeObject<Dictionary<string, List<AreaInfo>>>(json);
                Log.Information("从JSON文件加载数据成功");

                // 初始化内存字典
                内存字典.Clear();

                foreach (var area in 配置字典)
                {
                    var areaName = area.Key;
                    var areaInfoList = new List<AreaInfo2>();

                    foreach (var areaInfo in area.Value)
                    {
                        var areaInfo2 = new AreaInfo2
                        {
                            区域一 = new Dictionary<string, Vector3>(),
                            区域二 = new Dictionary<string, Vector3>(),
                            进入区域消息 = areaInfo.进入区域消息,
                            离开区域消息 = areaInfo.离开区域消息,
                            是否无敌 = areaInfo.是否无敌
                        };

                        // 转换区域一的坐标
                        foreach (var point in areaInfo.区域一)
                        {
                            string[] coords = point.Value.Split(',');
                            if (coords.Length == 3 &&
                                float.TryParse(coords[0], out float x) &&
                                float.TryParse(coords[1], out float y) &&
                                float.TryParse(coords[2], out float z))
                            {
                                areaInfo2.区域一[point.Key] = new Vector3(x, y, z);
                            }
                            else
                            {
                                Log.Warning($"区域 '{areaName}' 的区域一坐标 '{point.Value}' 格式不正确");
                            }
                        }

                        // 转换区域二的坐标
                        foreach (var point in areaInfo.区域二)
                        {
                            string[] coords = point.Value.Split(',');
                            if (coords.Length == 3 &&
                                float.TryParse(coords[0], out float x) &&
                                float.TryParse(coords[1], out float y) &&
                                float.TryParse(coords[2], out float z))
                            {
                                areaInfo2.区域二[point.Key] = new Vector3(x, y, z);
                            }
                            else
                            {
                                Log.Warning($"区域 '{areaName}' 的区域二坐标 '{point.Value}' 格式不正确");
                            }
                        }

                        areaInfoList.Add(areaInfo2);
                    }

                    内存字典[areaName] = areaInfoList;
                }
            }
            catch (Exception e)
            {
                Log.Error($"从JSON文件加载数据失败: {e.Message}");
            }

            // 遍历并打印加载的区域信息
            foreach (var area in 内存字典)
            {
                Log.Information("区域：[" + area.Key);
                foreach (var areaInfo in area.Value)
                {
                    Log.Information(area.Key + "]进入区域信息：" + areaInfo.进入区域消息);
                    Log.Information(area.Key + "]离开区域信息：" + areaInfo.离开区域消息);
                    Log.Information(area.Key + "是否无敌:" + areaInfo.是否无敌);
                    foreach (var point in areaInfo.区域一)
                    {
                        Log.Information(area.Key + "的" + point.Key + "↓");
                        Log.Information(point.Value.ToString());
                    }
                    foreach (var point in areaInfo.区域二)
                    {
                        Log.Information(area.Key + "的" + point.Key + "↓");
                        Log.Information(point.Value.ToString());
                    }
                }
            }
        }

        public override string Name => "区域插件";

        public byte FirstLevel => 1;

        public void InitCreatureTypes(SubsystemCreatureSpawn subsystemCreatureSpawn, List<SubsystemCreatureSpawn.CreatureType> creatureTypes)
        {
        }

        public override void Initialize()
        {
            CreatureSpawnEventManager.AddObject(this);
            PlayerEnterGameEventManager.AddObject(this);
            CreatureHealthEventManager.AddObject(this);
            初始化();
            加载配置();
        }

        public override void Load()
        {
            SubsystemPlayers = GameManager.Project.FindSubsystem<SubsystemPlayers>();
        }

        public void OnEntityAdded(SubsystemCreatureSpawn subsystemCreatureSpawn, Entity entity)
        {
        }

        public void OnEntityRemoved(SubsystemCreatureSpawn subsystemCreatureSpawn, Entity entity)
        {
        }

        public void OnPlayerSpawned(PlayerData playerData, Entity playerEntity, Vector3 position)
        {
            
        }

        public override void Save()
        {
        }

        public bool Update(SubsystemCreatureSpawn subsystemCreatureSpawn, float dt) //
        {
            foreach (ComponentPlayer player in SubsystemPlayers.ComponentPlayers)
            {
                Vector3 玩家位置 = player.ComponentBody.Position;
                bool 在区域内 = false;

                // 遍历所有区域检查
                foreach (var 区域 in 内存字典)
                {
                    string 区域名称 = 区域.Key;
                    
                    foreach (var 区域信息 in 区域.Value)
                    {
                        if (区域信息.区域一.ContainsKey("最低点") && 区域信息.区域二.ContainsKey("最高点"))
                        {
                            Vector3 最低点 = 区域信息.区域一["最低点"];
                            Vector3 最高点 = 区域信息.区域二["最高点"];

                            if (IsPlayerInArea(最低点, 最高点, player))
                            {
                                在区域内 = true;

                                // 如果玩家之前不在这个区域
                                if (!玩家当前区域.ContainsKey(player) || 玩家当前区域[player] != 区域名称)
                                {
                                    // 发送进入区域消息
                                    if (!string.IsNullOrEmpty(区域信息.进入区域消息))
                                    {
                                        DisplaySmallMessageNet(player, 区域信息.进入区域消息);                                                                               
                                    }
                                    玩家当前区域[player] = 区域名称;
                                }
                                break;
                            }
                        }
                    }

                    if (在区域内) break;
                }

                // 如果不在任何区域内，但之前记录在某个区域
                if (!在区域内 && 玩家当前区域.ContainsKey(player))
                {
                    string 离开的区域 = 玩家当前区域[player];
                    // 查找离开的区域信息
                    if (内存字典.ContainsKey(离开的区域))
                    {
                        foreach (var 区域信息 in 内存字典[离开的区域])
                        {
                            if (!string.IsNullOrEmpty(区域信息.离开区域消息))
                            {
                                DisplaySmallMessageNet(player, 区域信息.离开区域消息);
                            }
                            break;
                        }
                    }

                    玩家当前区域.Remove(player);
                }
            }
            return true;
        }

        public bool IsPlayerInArea(Vector3 position1, Vector3 position2, ComponentPlayer componentPlayer)
        {
            Vector3 playerPos = componentPlayer.ComponentBody.Position;

            // 计算区域的min和max坐标
            float minX = Math.Min(position1.X, position2.X);
            float maxX = Math.Max(position1.X, position2.X);
            float minY = Math.Min(position1.Y, position2.Y);
            float maxY = Math.Max(position1.Y, position2.Y);
            float minZ = Math.Min(position1.Z, position2.Z);
            float maxZ = Math.Max(position1.Z, position2.Z);

            // 检查玩家是否在区域内
            return playerPos.X >= minX && playerPos.X <= maxX &&
                   playerPos.Y >= minY && playerPos.Y <= maxY &&
                   playerPos.Z >= minZ && playerPos.Z <= maxZ;
        }

        public void DisplaySmallMessageNet(ComponentPlayer componentPlayer, string text)
        {
            var messagePackget = new MessagePackage(null, text, 0, null);
            messagePackget.To = componentPlayer.PlayerData.Client;
            CommonLib.Net.QueuePackage(messagePackget);
        }

        public void PlayerEnter(PlayerData playerData)
        {

        }

        public void PlayerLeave(PlayerData playerData)
        {
            // 玩家离开游戏时的处理
            var player = playerData.ComponentPlayer;
            if (player != null && 玩家当前区域.ContainsKey(player))
            {
                玩家当前区域.Remove(player);
            }
        }

        public bool Heal(ComponentHealth componentHealth, float amount)
        {
            return true;
        }

        public bool Injure(ComponentHealth componentHealth, float amount, ComponentCreature attacker, string cause)
        {
            ComponentPlayer componentPlayerra = componentHealth.Entity.FindComponent<ComponentPlayer>();
            if(componentPlayerra != null) 
            {
                foreach (var area in 内存字典)
                {
                    foreach (var areaInfo in area.Value)
                    {
                        if (areaInfo.是否无敌)
                        {
                            if (IsPlayerInArea(areaInfo.区域一["最低点"], areaInfo.区域二["最高点"], componentPlayerra))
                            {
                                return false;
                            }
                        }
                    }
                }
            }
            return true;
        }
    }

    public class dd
    {
        public void da(ComponentPlayer componentPlayer)
        {
            componentPlayer.ComponentHealth.FallResilience = 0.0f;//q 0.0f 无敌 跌倒后无敌
            componentPlayer.ComponentHealth.Injure(componentPlayer.ComponentHealth.FallResilience,componentPlayer, false,"666"); // 伤害 666 
        }
    }

}